package com.tust.androidbbsclient.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.tust.androidbbsclient.ArticleDetailActivity;
import com.tust.androidbbsclient.R;
import com.tust.androidbbsclient.tool.Tool;
import com.tust.androidbbsclient.trans.MessageList;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class MessageMsgListRecyclerAdapter extends RecyclerView.Adapter<MessageMsgListViewHolder> {
    private Toast toast;
    private Context context;
    private Fragment fragment;
    private List<MessageList> messageLists;

    //有参构造函数
    public MessageMsgListRecyclerAdapter(Context context, Fragment fragment, List<MessageList> messageLists) {
        this.context = context;
        this.fragment = fragment;
        this.messageLists = messageLists;
    }

    @NonNull
    @Override
    public MessageMsgListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.recycleitem_message_msglist, parent, false);
        MessageMsgListViewHolder messageMsgListViewHolder = new MessageMsgListViewHolder(view);

        return messageMsgListViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MessageMsgListViewHolder holder, int position) {
        MessageList itemdata = messageLists.get(position);

        //填充数据源
        holder.textViewMsgListMsgID.setText(String.valueOf(itemdata.getMsgID()));
        holder.textViewMsgListArtID.setText(String.valueOf(itemdata.getArtID()));
        holder.textViewMsgListMsgSenderName.setText(itemdata.getMsgSenderName());
        holder.textViewMsgListMsgContent.setText(itemdata.getMsgContent());
        holder.textViewMsgListMsgTime.setText(itemdata.getMsgTime());
        if (itemdata.getMsgIsReaded() == 0) {
            holder.textViewMsgListMsgIsReaded.setText("未\n读");
            holder.linearLayoutMsgListMsgIsReaded.setAlpha(1);
        }
        else {
            holder.textViewMsgListMsgIsReaded.setText("已\n读");
            holder.linearLayoutMsgListMsgIsReaded.setAlpha(0.5F);
        }

        //RecyclerView子项左侧布局监听事件
        holder.linearLayoutMsgList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (holder.textViewMsgListArtID.getText().toString().equals("-1")) ;//消息不含贴文ID
                else {
                    showToast(Tool.addEmoji() + "正在打开贴文！");

                    //跳转活动，带有ArtID参数
                    Intent intent = new Intent(context, ArticleDetailActivity.class);
                    intent.putExtra("ArtID", Integer.valueOf(holder.textViewMsgListArtID.getText().toString()));
                    context.startActivity(intent);
                    fragment.getActivity().overridePendingTransition(R.anim.fade_out,R.anim.fade_in);//改变跳转活动动画，淡出淡入
                }

                holder.readMsgThread();//发送阅读消息请求子线程
            }
        });
    }

    @Override
    public int getItemCount() {
        return messageLists.size();
    }

    @Override
    public int getItemViewType(int position) {
        return 0;
    }

    //Toast消息提示框显示方法
    private void showToast(String s) {
        if (toast == null){
            toast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
        }else {
            toast.cancel();
            toast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
        }
        toast.show();
    }
}

//ViewHolder类
class MessageMsgListViewHolder extends RecyclerView.ViewHolder {
    private Toast toast;

    //数据视图组件
    LinearLayout linearLayoutMsgList;
    LinearLayout linearLayoutMsgListMsgIsReaded;
    TextView textViewMsgListMsgID;
    TextView textViewMsgListArtID;
    TextView textViewMsgListMsgSenderName;
    TextView textViewMsgListMsgTime;
    TextView textViewMsgListMsgContent;
    TextView textViewMsgListMsgIsReaded;

    //用于在线程间传递消息
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);//获取子线程传递的消息
            if (msg.what == 1) {//阅读消息请求返回值
                String strMsg = msg.obj.toString();
                System.out.println("阅读消息：" + strMsg);

                if (strMsg.equals("serverFalse")) showToast(Tool.addEmoji() + "服务器通信失败！");
                else if (strMsg.equals("readMsgFalse")) showToast(Tool.addEmoji() + "阅读消息失败！");
                else if (strMsg.equals("readMsgSuccess")) {
                    showToast(Tool.addEmoji() + "阅读消息成功！");

                    textViewMsgListMsgIsReaded.setText("已\n读");
                    linearLayoutMsgListMsgIsReaded.setAlpha(0.5F);
                }
            }
        }
    };

    public MessageMsgListViewHolder(@NonNull View itemView) {
        super(itemView);

        //绑定RecyclerView子项的控件
        linearLayoutMsgList = itemView.findViewById(R.id.ll_msgList);
        textViewMsgListMsgID = itemView.findViewById(R.id.tv_msgListMsgID);
        textViewMsgListArtID = itemView.findViewById(R.id.tv_msgListArtID);
        linearLayoutMsgListMsgIsReaded = itemView.findViewById(R.id.ll_msgListMsgIsReaded);
        textViewMsgListMsgSenderName = itemView.findViewById(R.id.tv_msgListMsgSenderName);
        textViewMsgListMsgTime = itemView.findViewById(R.id.tv_msgListMsgTime);
        textViewMsgListMsgContent = itemView.findViewById(R.id.tv_msgListMsgContent);
        textViewMsgListMsgIsReaded = itemView.findViewById(R.id.tv_msgListMsgIsReaded);

        //RecyclerView子项未读文本监听事件
        textViewMsgListMsgIsReaded.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (textViewMsgListMsgIsReaded.getText().toString().equals("未\n读")) {
                    showToast(Tool.addEmoji() + "点击未读按钮！");

                    readMsgThread();//发送阅读消息请求子线程
                }
            }
        });
    }

    //发送阅读消息请求子线程方法
    protected void readMsgThread() {
        new Thread() {
            @Override
            public void run() {
                OutputStream outputStream = null;
                BufferedReader bufferedReader = null;
                String data = "";
                try {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 1;//增加handlerMsg标识符

                    URL url = new URL(Tool.InetAddress + "/readMsg.do");//请求地址
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //连接类相关设置
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(3000);//连接服务器超时
                    connection.setReadTimeout(3000);//从服务器读取数据超时
                    connection.setDoInput(true);//允许写入，从服务端读取结果流
                    connection.setDoOutput(true);//允许写出，开启Post请求体
                    connection.setUseCaches(false);//不使用Cache
                    connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                    connection.connect();//连接网络
                    String params = "MsgID=" + textViewMsgListMsgID.getText().toString();//请求体内容
                    outputStream = connection.getOutputStream();//请求输出流
                    outputStream.write(params.getBytes());

                    int code = connection.getResponseCode();//获得响应状态码
                    if (code == 200) {//返回状态码200，连接成功
                        bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        data = bufferedReader.readLine();

                        handlerMsg.obj = data;//写入线程传递消息
                    } else handlerMsg.obj = "serverFalse";//服务器通信失败
                    connection.disconnect();//关闭连接

                    handler.sendMessage(handlerMsg);//发送线程消息
                } catch (IOException e) {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 1;//增加handlerMsg标识符
                    handlerMsg.obj = "serverFalse";
                    handler.sendMessage(handlerMsg);

                    //throw new RuntimeException(e);
                } finally {
                    try {
                        if (bufferedReader != null) bufferedReader.close();
                        if (outputStream != null) {
                            outputStream.flush();
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        System.out.println("子线程：finally失败");
                        //throw new RuntimeException(e);
                    }
                }
            }
        }.start();
    }

    //Toast消息提示框显示方法
    private void showToast(String s) {
        if (toast == null){
            toast = Toast.makeText(itemView.getContext(), s, Toast.LENGTH_SHORT);
        }else {
            toast.cancel();
            toast = Toast.makeText(itemView.getContext(), s, Toast.LENGTH_SHORT);
        }
        toast.show();
    }
}
